<template>
  <div class="page-setting">
    <div class="crumbs">
      <router-link to="/">首页</router-link> / <span>系统设置</span> /
      <span class="active">大屏设置</span>
    </div>
    <el-container :style="{ height: mainH + 'px' }">
      <el-main class="census-main setting-iot">
        <div class="set-item">
          <h2>大屏背景</h2>
          <el-form ref="bgForm" label-width="100px">
            <el-form-item label="背景图片：">
              <!-- <el-upload
                class="upload-image"
                :action="uploadUrl"
                list-type="picture-card"
                :show-file-list="false"
                :limit="1"
                accept="image/*"
                :on-success="(res) => handleUploadSuccess(res, 'bg')"
                :on-preview="handlePictureCardPreview"
                :disabled="!$store.getters.hasEditPermission"
              >
                <img v-if="bgPath" :src="bgPath" class="bg-img" />
                <i v-else class="el-icon-plus"></i>
              </el-upload> -->
              <el-upload
                class="upload-demo"
                :action="uploadUrl"
                :on-success="(res) => handleUploadSuccess(res, 'bg')"
                :on-preview="handlePictureCardPreview"
                :show-file-list="false"
                accept="image/*"
                :data="{ token: siteInfos.token }"
              >
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
              <span class="icon-tip color-red">推荐尺寸1920*1080</span>
              <div class="mt-10" style="width: 50%" v-if="bgPath">
                <floorMarker
                  :img="bgPath"
                  :coordList="coordinateData"
                  height="auto"
                ></floorMarker>
              </div>
            </el-form-item>
            <el-form-item label="默认：">
              <el-radio-group v-model="defaultOption">
                <el-radio :label="1">地图</el-radio>
                <el-radio :label="2">背景</el-radio>
                <el-radio :label="3">混合</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item :label="isAdmin ? '单位列表：' : '设备列表：'">
              <ul class="device-list mb-10" v-if="coordinateData.length !== 0">
                <li v-for="(item, index) in coordinateData" :key="index">
                  <p class="flex-1">{{ item.deviceName }}</p>
                  <p class="color-gray mr-10">
                    坐标：{{ item.x }},{{ item.y }}
                  </p>
                  <el-button
                    size="mini"
                    type="green"
                    @click="markDevice(item)"
                    :disabled="!$store.getters.hasEditPermission"
                    >标注位置</el-button
                  >
                  <el-button
                    size="mini"
                    type="danger"
                    @click="deleteDevice(index)"
                    :disabled="!$store.getters.hasEditPermission"
                    >删除</el-button
                  >
                </li>
              </ul>
              <el-button type="primary" @click="openDeviceModal">
                {{ isAdmin ? "添加单位" : "添加设备" }}
              </el-button>
            </el-form-item>
            <el-form-item label="">
              <el-button
                type="primary"
                :loading="bgSaving"
                @click="saveBgAction"
              >
                提交
              </el-button>

              <!-- :loading="bgSaving" -->
              <el-button type="cancel" @click="clearAction(1)">
                清空
              </el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="set-item">
          <h2>报警音频</h2>
          <el-form ref="audioForm" label-width="130px">
            <el-form-item label="已上传音频：">
              <audio :src="audioPath" controls v-if="audioPath"></audio>
              <p v-else>暂未上传</p>
            </el-form-item>
            <el-form-item label="音频文件：">
              <el-upload
                ref="upload"
                class="upload-file"
                :action="uploadUrl"
                :show-file-list="false"
                :limit="1"
                :on-success="(res) => handleUploadSuccess(res, 'audio')"
                :auto-upload="true"
                accept=".wav,.mp3"
                name="file"
                :data="{ token: siteInfos.token }"
              >
                <el-button
                  size="small"
                  type="blue"
                  :disabled="!$store.getters.hasEditPermission"
                >
                  {{ audioPath ? "点击更换" : "点击上传" }}
                </el-button>
              </el-upload>
              <span class="icon-tip color-red">推荐格式：.mp3,.wav</span>
            </el-form-item>
            <el-form-item label="">
              <el-button
                type="primary"
                :loading="audioSaving"
                @click="saveAudioAction"
              >
                提交
              </el-button>
              <!-- :loading="bgSaving" -->
              <el-button type="cancel" @click="clearAction(2)">
                清空
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-main>
    </el-container>

    <el-dialog
      :visible.sync="previewVisible"
      v-if="previewVisible"
      append-to-body
    >
      <img style="max-width: 100%" :src="bgPath" alt="" />
    </el-dialog>
    <!-- 选择设备 弹窗 start -->
    <el-dialog
      title="选择设备"
      v-if="deviceVisible"
      :visible.sync="deviceVisible"
      width="1000px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      destroy-on-close
      append-to-body
    >
      <FlooDeviceSelect
        :coordinateData="coordinateData"
        @select="onDeviceSelect"
        setting
      ></FlooDeviceSelect>
    </el-dialog>
    <!-- 选择设备 弹窗 end -->
    <!-- 标注设备位置弹窗 start -->
    <div class="floor-marker-modal" v-if="markerVisible">
      <p>在图片上点击鼠标左键添加设备位置</p>
      <floorMarker
        :img="bgPath"
        :activeDevice="activeDevice"
        :markable="true"
        ref="floorMarker"
      ></floorMarker>
      <div class="text-center">
        <el-button size="small" type="default" @click="markerVisible = false"
          >取消</el-button
        >
        <el-button
          size="small"
          type="primary"
          @click="confirmMarker"
          :disabled="!$store.getters.hasEditPermission"
          >确定</el-button
        >
      </div>
    </div>
    <!-- 标注设备位置弹窗 end -->
  </div>
</template>

<script>
import { mapState } from "vuex";
import floorMarker from "@/components/archive/FloorMarker";
import FlooDeviceSelect from "@/components/archive/FloorDeviceSelect";
export default {
  name: "IOTSetting",
  components: {
    FlooDeviceSelect,
    floorMarker,
  },
  props: {
    winH: {
      type: Number,
      default: 500,
    },
  },
  data() {
    return {
      loading: false,
      orgId: "",
      bgSaving: false,
      audioSaving: false,
      uploadUrl: this.config.uploadUrl,
      bgPath: "",
      audioPath: "",
      previewVisible: false,
      defaultAudoSrc: require("@/assets/audio/620.wav"),
      defaultOption: 1,
      coordinateData: [],
      deviceVisible: false,
      markerVisible: false,
      activeDevice: null,
    };
  },
  computed: {
    mainH() {
      return this.winH - 219;
    },
    ...mapState(["siteInfos"]),
    isAdmin() {
      return this.siteInfos && this.siteInfos.userType == 1;
    },
  },
  created() {
    this.getData();
  },
  methods: {
    getData() {
      this.loading = true;
      this.$get("/systemsetup/systemsetup/largeScreenList").then(
        (res) => {
          this.loading = false;
          const audio = res.data.find((item) => item.type == 2);
          if (audio) {
            this.audioPath = audio.file;
          }
          const bg = res.data.find((item) => item.type == 1);
          if (bg) {
            this.bgPath = bg.file;
            this.defaultOption = bg.defaultOption;
            this.coordinateData = bg.coordinateData;
          }
        },
        (err) => {
          this.loading = false;
          if (err.msg) {
            this.$message.error(err.msg);
          }
        }
      );
    },

    handlePictureCardPreview(file) {
      this.previewImageUrl = file.url;
      this.previewVisible = true;
    },
    handleUploadSuccess(res, type) {
      const { filePath, fileName } = res.data;
      if (type == "bg") {
        this.bgPath = filePath;
      } else {
        this.audioPath = filePath;
      }
    },
    saveBgAction() {
      if (this.defaultOption == 2 && this.bgPath == "") {
        this.$message.error("请上传图片");
        return;
      }
      this.submitAction({
        fileUrl: this.bgPath,
        type: 1,
        defaultOption: this.defaultOption,
        coordinateData: this.coordinateData,
      });
    },
    saveAudioAction() {
      if (!this.audioPath) {
        this.$message.error("请上传音频文件");
        return;
      }
      this.submitAction({
        fileUrl: this.audioPath,
        type: 2,
      });
    },
    submitAction(formData) {
      if (formData.type == 1) {
        this.bgSaving = true;
      } else {
        this.audioSaving = true;
      }
      this.$post("/systemsetup/systemsetup/largeScreenSettings", formData).then(
        (res) => {
          if (formData.type == 1) {
            this.bgSaving = false;
            const temp = ["amap", "bgImg", "bigmap"];
            this.$store.commit("setMapType", temp[this.defaultOption - 1]);
          } else {
            this.audioSaving = false;
          }
          this.$message.success("保存成功");
        },
        (err) => {
          if (formData.type == 1) {
            this.bgSaving = false;
          } else {
            this.audioSaving = false;
          }
          if (err.msg) {
            this.$message.error(err.msg);
          }
        }
      );
    },
    clearAction(type) {
      this.showConfirm(
        `确定要清空${type == 1 ? "大屏背景" : "报警音频"}吗？`,
        () => {
          if (type == 1) {
            this.bgSaving = true;
          } else {
            this.audioSaving = true;
          }
          this.$post("/systemsetup/systemsetup/largeScreenDel", { type }).then(
            (res) => {
              if (type == 1) {
                this.bgSaving = false;
                this.bgPath = "";
                this.coordinateData = [];
                this.$store.commit("setMapType", "amap");
              } else {
                this.audioSaving = false;
                this.audioPath = "";
              }
              this.$message.success("清空成功");
              this.defaultOption = 1;
            },
            (err) => {
              if (type == 1) {
                this.bgSaving = false;
              } else {
                this.audioSaving = false;
              }
              if (err.msg) {
                this.$message.error(err.msg);
              }
            }
          );
        }
      );
    },
    // 打开设备列表弹窗
    openDeviceModal() {
      this.deviceVisible = true;
    },
    onDeviceSelect(array) {
      this.coordinateData = array.map((item) => {
        return {
          deviceId: this.isAdmin ? item.id : item.number,
          deviceName: item.name,
          x: 0,
          y: 0,
        };
      });
      this.deviceVisible = false;
    },
    // 删除设备
    deleteDevice(index) {
      this.showConfirm("确定删除该设备吗？", () => {
        this.coordinateData.splice(index, 1);
      });
    },
    // 标注
    markDevice(item) {
      if (!this.bgPath) {
        this.$message.error("请上传平面图");
        return;
      }
      this.activeDevice = item;
      this.markerVisible = true;
    },
    confirmMarker() {
      const newMarker = this.$refs.floorMarker.getNewMarker();
      if (!newMarker) {
        this.$message.error("请标注位置");
        return;
      }
      this.activeDevice.x = newMarker.x;
      this.activeDevice.y = newMarker.y;
      this.markerVisible = false;
    },
  },
};
</script>
<style lang="less" scoped>
.marker-img {
  width: 50%;
  & > img {
    display: block;
    width: 100%;
  }
}
.device-list {
  padding: 0 10px;
  border: 1px solid rgba(255, 255, 255, 0.5);
  & > li {
    display: flex;
    align-items: center;
    height: 50px;
    border-bottom: 1px solid rgba(255, 255, 255, 0.2);
    &:last-child {
      border-bottom: none;
    }
  }
}
</style>
